package org.zwy.gradetrack.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.CourseScore;
import org.zwy.gradetrack.entity.User;
import org.zwy.gradetrack.service.CourseScoreService;
import org.zwy.gradetrack.service.UserService;
import org.zwy.gradetrack.vo.CourseScoreVo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程得分控制器
 */
@RestController
@RequestMapping("/api/course-score")
public class CourseScoreController {

    private static final Logger logger = LoggerFactory.getLogger(CourseScoreController.class);

    @Autowired
    private CourseScoreService courseScoreService;

    @Autowired
    private UserService userService;

    /**
     * 获取课程得分列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER', 'GRADUATE')")
    public Result<List<CourseScoreVo>> getCourseScores(
            @RequestParam(required = false) String courseCode,
            @RequestParam(required = false) String courseName,
            @RequestParam(required = false) String courseType) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();

        User currentUser = userService.lambdaQuery().eq(User::getUsername, username).one();

        Long graduateId = null;
        if (currentUser != null && currentUser.getRoles() != null) {
            // 如果是毕业生，则只能查询自己的成绩
            if (currentUser.getRoles().stream().map(role -> role.getRoleCode()).collect(Collectors.toList()).contains("GRADUATE")) {
                graduateId = currentUser.getId();
            }
        }

        logger.info("接收到获取课程得分列表请求，graduateId: {}, courseCode: {}, courseName: {}, courseType: {}",
                graduateId, courseCode, courseName, courseType);
        try {
            List<CourseScoreVo> scores = courseScoreService.getStudentCourseScores(graduateId, courseCode, courseName, courseType);
            logger.info("成功获取课程得分列表，数量: {}", scores.size());
            return Result.success(scores);
        } catch (Exception e) {
            logger.error("获取课程得分列表失败", e);
            return Result.error(500, "获取课程得分列表失败：" + e.getMessage());
        }
    }

    /**
     * 添加课程得分
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<CourseScore> createCourseScore(@RequestBody CourseScore courseScore) {
        logger.info("接收到添加课程得分请求: {}", courseScore);
        try {
            CourseScore savedScore = courseScoreService.saveOrUpdateScore(courseScore);
            logger.info("成功添加课程得分: {}", savedScore);
            return Result.success(savedScore);
        } catch (RuntimeException e) {
            logger.error("添加课程得分失败", e);
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 更新课程得分
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<CourseScore> updateCourseScore(@PathVariable Long id, @RequestBody CourseScore courseScore) {
        logger.info("接收到更新课程得分请求，id: {}, courseScore: {}", id, courseScore);
        try {
            // 确保ID一致性
            courseScore.setId(id);
            CourseScore updatedScore = courseScoreService.saveOrUpdateScore(courseScore);
            logger.info("成功更新课程得分: {}", updatedScore);
            return Result.success(updatedScore);
        } catch (RuntimeException e) {
            logger.error("更新课程得分失败", e);
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 删除课程得分
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Void> deleteScore(@PathVariable Long id) {
        logger.info("接收到删除课程得分请求，id: {}", id);
        try {
            if (!courseScoreService.lambdaQuery()
                    .eq(CourseScore::getId, id)
                    .exists()) {
                logger.error("课程得分记录不存在，id: {}", id);
                return Result.error(404, "课程得分记录不存在");
            }

            courseScoreService.removeById(id);
            logger.info("成功删除课程得分记录，id: {}", id);
            return Result.success();
        } catch (Exception e) {
            logger.error("删除课程得分记录失败", e);
            return Result.error(500, "删除课程得分记录失败：" + e.getMessage());
        }
    }
} 